package com.njwb.Swing.Users;

import com.njwb.Util.UtilService;
import com.njwb.pojo.Users;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;

public class UserController {
    private final UserView view;
    private final UtilService utilService;

    public UserController(UserView view, UtilService utilService) {
        this.view = view;
        this.utilService = utilService;

        initActions();
        loadData();
    }

    private void initActions() {
        // 搜索
        view.getSearchButton().addActionListener(e -> {
            String name = view.getSearchField().getText().trim();
            if (name.isEmpty()) loadData();
            else loadDataByName(name);
        });

        // 新增
        view.getAddButton().addActionListener(e -> {
            AddUserDialog dialog = new AddUserDialog(
                    (Frame) SwingUtilities.getWindowAncestor(view),
                    utilService,
                    this::loadData
            );
            dialog.setVisible(true);
        });

        // 修改
        view.getEditButton().addActionListener(e -> {
            int selectedRow = view.getUserTable().getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(view, "请先选择要修改的用户！");
                return;
            }
            Users user = new Users(
                    (int) view.getTableModel().getValueAt(selectedRow, 0),
                    (String) view.getTableModel().getValueAt(selectedRow, 1),
                    (String) view.getTableModel().getValueAt(selectedRow, 2),
                    (String) view.getTableModel().getValueAt(selectedRow, 3),
                    (int) view.getTableModel().getValueAt(selectedRow, 4),
                    (String) view.getTableModel().getValueAt(selectedRow, 5),
                    (String) view.getTableModel().getValueAt(selectedRow, 6),
                    "管理员".equals(view.getTableModel().getValueAt(selectedRow, 7)) ? 1 : 0
            );
            EditUserDialog dialog = new EditUserDialog(
                    (Frame) SwingUtilities.getWindowAncestor(view),
                    utilService,
                    user,
                    this::loadData
            );
            dialog.setVisible(true);
        });

        // 删除
        view.getDeleteButton().addActionListener(e -> {
            int[] selectedRows = view.getUserTable().getSelectedRows();
            if (selectedRows.length == 0) {
                JOptionPane.showMessageDialog(view, "请先选择要删除的用户！");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(
                    view,
                    "确定删除选中的用户吗？",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION
            );
            if (confirm != JOptionPane.YES_OPTION) return;

            boolean allSuccess = true;
            for (int row : selectedRows) {
                int userId = (int) view.getTableModel().getValueAt(row, 0);
                if (!utilService.deleteUser(userId)) {
                    allSuccess = false;
                }
            }
            JOptionPane.showMessageDialog(view, allSuccess ? "删除成功！" : "部分用户删除失败！",
                    allSuccess ? "提示" : "警告",
                    allSuccess ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.WARNING_MESSAGE);
            loadData();
        });
    }

    // 加载全部数据
    public void loadData() {
        ArrayList<Users> list = utilService.getAllUsers();
        refreshTable(list);
    }

    // 根据用户名搜索
    public void loadDataByName(String name) {
        ArrayList<Users> list = utilService.getUsersByUsername(name);
        refreshTable(list);
    }

    private void refreshTable(ArrayList<Users> list) {
        DefaultTableModel model = view.getTableModel();
        model.setRowCount(0);
        for (Users u : list) {
            model.addRow(new Object[]{
                    u.getId(), u.getUsername(), u.getPassword(),
                    u.getGender(), u.getAge(), u.getPhone(),
                    u.getAddress(), u.getRole() == 1 ? "管理员" : "普通用户"
            });
        }
    }
}
